package com.hbsi.demo3;

import com.hbsi.demo2.Person;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

import static java.lang.System.setProperty;

/**
 * @author 程奕红
 * @version 1.0
 */
@SuppressWarnings("all")
public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //1.传统方法：防止因为需求的改变，导致代码需要改
        Student student=new Student();
        student.display();

        //2.读取配置文件，利用反射机制来创建对象，调用方法
        Properties properties=new Properties();
//        properties.load(new FileInputStream("src/work.properties"));
        InputStream is=Test.class.getClassLoader().getResourceAsStream("work.properties");
        properties.load(is);
        String className=properties.getProperty("className");//要创建对象的类型的名字
        String methodName=properties.getProperty("methodName");//要调用的方法名
//        String className=properties.get("className").toString();
//        String method=properties.get("methodName").toString();
//        System.out.println("className="+className);
//        System.out.println("method="+method);
        Class c1=Class.forName(className);
        Constructor constructor=c1.getConstructor();
        Object object=constructor.newInstance();

        Method method=c1.getMethod(methodName);
        method.invoke(object);
        Person p=new Person();
        set(p,"address","保定");
        System.out.println(p);

    }
    //静态的工具类，可以给任意对象的任意属性赋值
    public static void set(Object object,String name,Object val) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException, NoSuchFieldException {
        Class classz = object.getClass();
        Field field=classz.getDeclaredField(name);

        field.setAccessible(true);
        field.set(object,val);

    }
}
